<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <!-- :inline="true" - 行内表单 -->
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyWords" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="onsale">上架</el-button>
          <el-button type="warning" @click="offsale">下架</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <!--列表-->
    <el-table :data="pets" highlight-current-row v-loading="listLoading"
              @selection-change="selsChange" style="width: 100%;">
      <!-- 批量删除：type="selection - 选项 -->
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="title" label="寻主消息标题" width="150">
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" sortable>
        <template slot-scope="scope">
          <span style="color: green" v-if="scope.row.state==0">待审核</span>
          <!--span style="color: red" v-else-if="scope.row.state==1">下架</span>-->
        </template>
      </el-table-column>
      <el-table-column prop="name" label="名称" width="100">
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="100">
      </el-table-column>
      <el-table-column prop="gender" label="性别" width="100">
        <template slot-scope="scope">
          <span style="color: green" v-if="scope.row.gender==0">母</span>
          <span style="color: red" v-else-if="scope.row.gender==1">公</span>
        </template>
      </el-table-column>
      <el-table-column prop="coat_color" label="毛色" width="100">
      </el-table-column>
      <el-table-column prop="resources" label=图片介绍" width="100">
      </el-table-column>
      <el-table-column prop="petType.name" label="宠物类型" width="100">
      </el-table-column>
      <el-table-column prop="price" label="价格" width="100">
      </el-table-column>
      <el-table-column prop="address" label="地址" width="100">
      </el-table-column>
      <el-table-column prop="user.username" label="用户" width="100">
      </el-table-column>
      <el-table-column prop="shop.name" label="所属店铺" width="100">
      </el-table-column>
      <el-table-column prop="note" label="备注" width="100">
      </el-table-column>

<!--      <el-table-column label="操作" width="180">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small"
                     @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>-->
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <!--
        :disabled="this.sels.length===0" - 当没有选中任何选项就禁用
       -->
      <el-button type="danger" @click="batchRemove"
                 :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="pageSize" :total="totals" :current-page="currentPage" style="float:right;">
      </el-pagination>
    </el-col>

    <!--添加和修改的对话框-->
    <!--
      :close-on-click-modal="false" - 点击对话外面的区域不关闭对话框
      :model="saveForm" - 绑定表单数据
      :rules="saveFormRules" - 校验规则
      ref="saveForm" - 对话框的名称 - 验证的时候需要用
      auto-complete="off" - 自动完成
    -->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="宠物名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="销售价" prop="saleprice">
          <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价" prop="costprice">
          <el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">上架</el-radio>
            <el-radio class="radio" :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属店铺">
          <el-select v-model="saveForm.shop_id" placeholder="请选择" clearable>
            <el-option v-for="item in shops"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="宠物类型">
          <el-cascader v-model="saveForm.type"
                       :options="typeTree"
                       :props="{ checkStrictly: true, label: 'name',value:'id'}"
                       clearable></el-cascader>
        </el-form-item>

        <el-form-item prop="resources" label="宠物图片">
          <el-upload class="upload-demo"
                     action="http://localhost:8080/fastDfs"
                     :on-remove="handleRemove"
                     :on-success="handleSuccess"
                     :file-list="fileList"
                     list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <quill-editor v-model="saveForm.petDetail.intro" :options="quillOption" v-if="saveForm.petDetail">
          </quill-editor>
        </el-form-item>
        <el-form-item label="领养须知" prop="orderNotice" >
          <quill-editor v-model="saveForm.petDetail.adoptNotice" :options="quillOption" v-if="saveForm.petDetail">
          </quill-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from '../../common/js/quill-config';

export default {
  components: {
    quillEditor
  },
  data() {
    return {
      //import quillConfig from '../../common/js/quill-config':与之对应
      quillOption: quillConfig,

      //分页相关的数据
      pets: [],     //绑定到表格 - 显示列表数据 - 请求完成之后
      totals: 0,          //总数量 - 计算分页栏 -  请求完成之
      currentPage: 1,     //当前页 - 分页栏默认当前页显示
      pageSize: 5,        //每页显示的条数  - 计算分页栏
      listLoading: false, //表格上的加载框
      state:0,
      //高级查询的参数
      keyWords: '', //关键字查询

      //批量删除的数据
      sels: [],//列表选中列 - 用于装选中的对象

      //添加或修改的相关数据
      saveFormVisible: false,  //对话框是否显示：默认不显示
      saveLoading: false,      //对话框中的加载框/忙等框
      title: '',              //标题
      saveFormRules: {        //校验规则
        saleprice: [
          //在失去焦点的时候，校验name是否为空，如果为空，就会显示红色的请输入宠物的编号
          { required: true, message: '请输入销售价', trigger: 'blur' }
        ],
        costprice: [
          //在失去焦点的时候，校验name是否为空，如果为空，就会显示红色的请输入宠物的名称
          { required: true, message: '请输入成本价', trigger: 'blur' }
        ],
        name: [
          //在失去焦点的时候，校验name是否为空，如果为空，就会显示红色的请输入宠物的名称
          { required: true, message: '请输入宠物的名称', trigger: 'blur' }
        ],
      },
      //编辑界面数据
      saveForm: {
        id: null,
        name: '',
        costprice: 0,
        saleprice: 0,
        type_id: null,
        type: null,
        resources: '',
        state: 0,
        shop_id: null,
        petDetail:{
          intro:'',
          adoptNotice: ''
        }
      },

      shops: [],
      typeTree: [],
      //用于保存宠物图片资源
      fileList: []
    }
  },
  methods: {
    //1.分页查询：获取宠物列表
    getPets() {
      //传递的参数
      let para = {
        //分页参数
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        //高级查询参数 - 关键字
        keyWords: this.keyWords,
        state:this.state,
      };
      //页面一加载就显示加载框
      this.listLoading = true;
      this.$http.post("/searchMasterMsg",para).then(res => {
        //赋值总数量
        this.totals = res.data.totals;
        //当前页的数据
        this.pets = res.data.data;
        //关闭加载框
        this.listLoading = false;
      }).catch(res => {
        this.$message.error('系统繁忙，请稍后重试!!!');
      })
    },

    //2.点击某一页触发的方法
    handleCurrentChange(val) {
      //当前页
      this.currentPage = val;
      this.getPets();
    },

    //3.关键字查询
    keywordQuery(){
      //关键字查询从第一页开始显示
      this.currentPage = 1;
      this.getPets();
    },

    //4.删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '温馨提示', {
        type: 'warning'
      }).then(() => { //点击确认之后要执行的代码
        //显示加载框
        this.listLoading = true;
        //获取id
        var id = row.id;
        this.$http.delete("/pet/"+id).then(res => {
          if(res.data.success){//删除成功
            this.$message.success('删除成功'); //3s自动消失

            //如果时最后一页并且时最后一条数据的时候：当前页 = 当前页-1
            //最后一条数据：(this.totals - 1)%this.pageSize == 0
            //总页数：Math.ceil(this.totals/this.pageSize)
            var totalPage = Math.ceil(this.totals/this.pageSize);
            if(totalPage==this.currentPage && this.currentPage>1 && (this.totals - 1)%this.pageSize == 0){
              this.currentPage = this.currentPage - 1;
            }

            this.getPets();
          }else{
            this.$message.error('系统繁忙，请稍后重试【500】');
          }
          this.listLoading = false;//关闭加载框
        }).catch(res => {
          this.$message.error('系统繁忙，请稍后重试【400,404】');
        })
      }).catch(() => { //点击取消之后要执行的代码
      });
    },

    //5.选项改变的时候触发
    selsChange: function (sels) {
      //获取被选中的对象  - 集合
      this.sels = sels;
    },

    //6.批量删除
    batchRemove: function () {
      //获取被选中对象的id们
      var ids = this.sels.map(item => item.id); //[1,2,3]
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/pet",ids).then(res => {
          if(res.data.success){//删除成功
            this.$message.success('删除成功'); //3s自动消失
            this.currentPage = 1;
            this.getPets();
          }else{
            this.$message.error('系统繁忙，请稍后重试【500】');
          }
          this.listLoading = false;//关闭加载框
        }).catch(res => {
          this.$message.error('系统繁忙，请稍后重试【400,404】');
        })
      }).catch(() => {
      });
    },

    //7.点击添加按钮弹出对话框
    handleAdd: function () {
      this.saveForm = {
        id: null,
        name: '',
        costprice: 0,
        saleprice: 0,
        type_id: null,
        type: null,
        resources: null,
        state: 0,
        shop_id: null,
        petDetail:{ //petDetail
          intro:'',
          adoptNotice: ''
        }
      };
      this.title = " 添 加 ";

      this.fileList = [];

      this.getShops();
      this.getTypeTree();
      //显示对话框
      this.saveFormVisible = true;
    },

    //8.点击编辑按钮弹出对话框
    handleEdit: function (index, row) {
      //克隆：防止对象引用修改显示的数据
      this.saveForm = Object.assign({}, row);
      this.title = " 修 改 ";

      //判断一下：防止因type为null导致的异常
      if(this.saveForm.type){
        //对宠物类型回显的处理:{} - []
        var dirPath = this.saveForm.type.dirPath; //   /2/3/5 - [2,3,5]
        var arr = dirPath.split("/"); //  ["/","2","3","5"]
        var resultArr = [];
        for(var i=1;i<arr.length;i++){
          resultArr[i-1] = parseInt(arr[i]); //将字符串转成整数
          //第一次：resultArr[0] = arr[1] = 2;
          //第二次：resultArr[1] = arr[2] = 3
        }
        this.saveForm.type = resultArr; //[2,3,5]
      }

      //对fileList做处理 - 因为ileList用于做回显
      this.fileList = [];
      if(this.saveForm.resources){//有值
        let arr = this.saveForm.resources.split(",");
        for (var i = 0;i<arr.length;i++){
          this.fileList.push({"url":"http://123.207.27.208" + arr[i]});
        }
      }

      this.getShops();
      this.getTypeTree();

      //显示对话框
      this.saveFormVisible = true;
    },

    //9.点击提交按钮添加或修改数据
    saveSubmit: function () {
      //所有对话框中  一个名称为 saveForm的对话框  验证【上面的验证规则通过了 - 返回true，否则返回false】
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            let para = Object.assign({}, this.saveForm);

            //点击提交对类型的处理
            let typeArr = this.saveForm.type; //[2,3,5]
            if(typeArr){
              //前端传递type为数组，后端type接收的是PetType类型，如果不处理就会出现400
              para.type = null;
              //将修改之后的宠物类型id赋值给type_id  .length-1:下标
              para.type_id = typeArr[typeArr.length-1];
            }

            this.$http.put("/pet",para).then(res => {
              if(res.data.success){
                this.$message.success("操作成功");
                this.getPets();
              }else{
                this.$message.error("系统繁忙，请稍后重试【500】")
              }
              this.saveLoading = false;
              this.saveFormVisible = false;
            }).catch(res => {
              this.$message.error("系统繁忙，请稍后重试【400,404】")
            })
          });
        }
      });
    },

    getShops(){
      this.$http.get("/shop").then(res =>{
        this.shops = res.data;
      })
    },

    getTypeTree(){
      this.$http.get("/petType/typeTree").then(res =>{
        this.typeTree = res.data;
      })
    },

    //图片上传
    //上传一张图片的时候会出发
    handleSuccess(response, file, fileList){
      //{ success: true, message: "操作成功", resultObj: "/group1/M00/00/0D/CgAIC2KpiEyANWQZAADIJRxVcQ8663.jpg" }
      //console.log(response);
      //1.处理resources
      if(this.saveForm.resources){//有值
        this.saveForm.resources  = this.saveForm.resources + "," + response.resultObj;
      }else{
        this.saveForm.resources = response.resultObj;
      }

      //2.处理fileList - 回显的
      // /group1/M00/00/0D/CgAIC2KpiEyANWQZAADIJRxVcQ8663.jpg,/group1/M00/00/0D/CgAIC2KpiEyANWQZAADIJRxVcQ8663.jpg
      this.fileList = [];
      if(this.saveForm.resources){//有值
        let arr = this.saveForm.resources.split(",");
        for (var i = 0;i<arr.length;i++){
          this.fileList.push({"url":"http://123.207.27.208" + arr[i]});
        }
      }
    },

    //点击删除某一张图片的处理
    handleRemove: function (file, fileList) {
      //{url: "http://123.207.27.208/group1/M00/00/02/CgAIC2KevEeAX2T4AAEUusLjqqk161.png"}
      //console.log(file);
      //1.调用删除接口删除 fastdfs上的图片
      let url = file.url
      let path = url.substring(url.indexOf("/group1"));
      this.$http.delete("/fastDfs?path="+path).then(res=>{
        if(res.data.success){
          this.$message.success("删除成功");
        }else{
          this.$message.error("删除失败");
        }
      })

      //2.对resource做处理 ：加入path="/group1/MxVcQ8663.jpg"
      // /group1/M00cQ8663.jpg,/group1/MxVcQ8663.jpg,/group1/MxVcQ8663.jpg
      if(this.saveForm.resources){//只有值
        //["/group1/M00cQ8663.jpg","/group1/MxVcQ8663.jpg","/group1/MxVcQ8663.jpg"]
        let arr = this.saveForm.resources.split(",");
        for (var i = 0;i<arr.length;i++){
          if(arr[i] == path){
            //从i开始删除，向后删除1个
            arr.splice(i,1);
            break;
          }
        }
        this.saveForm.resources = arr.join(","); // /group1/M00cQ8663.jpg,/group1/MxVcQ8663.jpg
      }

      //3.对fileList做处理----回显
      this.fileList = [];
      if(this.saveForm.resources){//有值
        let arr = this.saveForm.resources.split(",");
        for (var i = 0;i<arr.length;i++){
          this.fileList.push({"url":"http://123.207.27.208" + arr[i]});
        }
      }
    },


    //上架
    onsale(){
      var ids = this.sels.map(item => item.id);
      //获取选中的行
      if(!this.sels || this.sels.length  <1){
        this.$message({ message: '老铁，你不选中数据，臣妾上架不了啊....',type: 'error'});
        return;
      }
      this.$confirm('确认上架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch('/pet/onsale',ids).then((res) => {
          this.listLoading = false;
          if(res.data.success){
            this.$message({
              message: '上架成功',
              type: 'success'
            });
          }else{
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }
          this.getPets();
        }).catch(res => {
          this.$message({
            message: "系统错误，请稍后重试!!!",
            type: 'error'
          });
        })
      }).catch(() => {
      });
    },

    //下架
    offsale(){
      var ids = this.sels.map(item => item.id);
      //获取选中的行
      if(!this.sels || this.sels.length  <1){
        this.$message({ message: '老铁，你不选中数据，臣妾下架不了啊....',type: 'error'});
        return;
      }
      this.$confirm('确认下架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch('/pet/offsale',ids).then((res) => {
          this.listLoading = false;

          if(res.data.success){
            this.$message({
              message: '下架成功',
              type: 'success'
            });
          }else{
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }
          this.getPets();
        }).catch(res => {
          this.$message({
            message: "系统错误，请稍后重试!!!",
            type: 'error'
          });
        })
      }).catch(() => {
      });
    },


  },
  mounted() {
    this.getPets();
  }
}

</script>

<style scoped>
</style>